package com.controller;

import com.service.MessageConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.util.Map;

/**
 * WebSocket事件处理器
 */
@Component
public class WebSocketEventHandler {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventHandler.class);

    @Autowired
    private MessageConsumer messageConsumer;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 处理WebSocket连接事件
     */
    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = headerAccessor.getSessionId();
        
        logger.info("WebSocket连接建立: sessionId={}", sessionId);
        
        // 从连接参数中获取用户信息
        Map<String, Object> sessionAttributes = headerAccessor.getSessionAttributes();
        if (sessionAttributes != null && sessionAttributes.containsKey("openId")) {
            String openId = (String) sessionAttributes.get("openId");
            messageConsumer.setUserOnlineStatus(openId, true);
            logger.info("用户上线: openId={}, sessionId={}", openId, sessionId);
        }
    }

    /**
     * 处理WebSocket断开连接事件
     */
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = headerAccessor.getSessionId();
        
        logger.info("WebSocket连接断开: sessionId={}", sessionId);
        
        // 从连接参数中获取用户信息
        Map<String, Object> sessionAttributes = headerAccessor.getSessionAttributes();
        if (sessionAttributes != null && sessionAttributes.containsKey("openId")) {
            String openId = (String) sessionAttributes.get("openId");
            messageConsumer.setUserOnlineStatus(openId, false);
            logger.info("用户下线: openId={}, sessionId={}", openId, sessionId);
        }
    }
}
